package net.yyge.manifest.editor.tag;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import java.util.LinkedHashMap;
import java.util.Map;

public class UsesPermissionTag extends XmlTag {
    Map<String,Element> data=new LinkedHashMap<>();
    Document document;


    public UsesPermissionTag(Document document){
       this.document =document;
    }

    public UsesPermissionTag initPermission(Element element) {
        NamedNodeMap attributes = element.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if("android:name".equals(attribute.getNodeName())) {
               data.put(attribute.getNodeValue(), element);
            }
        }
        return this;
    }

    public UsesPermissionTag remove(String key){
        Element element = data.get(key);
        element.getParentNode().removeChild(element);
        return this;
    }
    public UsesPermissionTag add(String permission){
       // addAttribute(element,attrName,value);
        Element element = document.createElement("uses-permission");
        element.setAttribute("android:name",permission);
        data.put(permission, element);

        document.getElementsByTagName("manifest").item(0).appendChild(element);
        return this;
    }

    public UsesPermissionTag updateNamePackage(String oldPackageName,String packageName){
        for (String key : data.keySet()){
            Element element = data.get(key);
            String text = getAttrValue(element.getAttributes(), "android:name");
            if(text.contains(oldPackageName)){
                String replace = text.replace(oldPackageName, packageName);
                setValue(element,"android:name",replace);
            }
        }
        return this;
    }


}
